import config
from load_log import LoadLog, LogBlocks
from parse_build import ParseTargetBuildArg, TargetAttribute
import os
import sys

OUT_DIR = "./"

def ParseLogTarget(path):
    loader = LoadLog(path)
    projectName, logBlocks, logLines = loader.GetTargetLineBlock()
    targetsBuildArg = []
    print("任务数：{}".format(len(logBlocks)))
    for logBlock in logBlocks:
        ptba = ParseTargetBuildArg(projectName, logLines[logBlock[0] : logBlock[1]])
        targetArg = ptba.ParseTargetBuildPara()
        targetsBuildArg.append(targetArg)
    return targetsBuildArg

# TargetAttribute =  namedtuple('TargetAttribute', ['targetName', 'targetType', 'macro', 'includeDirs', 'compileOptsCC', 'compileOptsCXX', 'srcFiles', 'linkLibs'])
def _WriteSharedTarget(gnf, targetArgsD):
    gnf.write(config.OHOS_SHARED_TARGET_TEMPLATE.format(targetArgsD["targetName"], targetArgsD["srcFiles"], targetArgsD["linkLibs"], targetArgsD["projectName"]).replace("'", '"'))

def _WriteStaticTarget(gnf, targetArgsD):
    gnf.write(config.OHOS_STATIC_TARGET_TEMPLATE.format(targetArgsD["targetName"], targetArgsD["srcFiles"], targetArgsD["linkLibs"], targetArgsD["projectName"], ).replace("'", '"'))

def _WriteExecutableTarget(gnf, targetArgsD):
    gnf.write(config.OHOS_EXE_TARGET_TEMPLATE.format(targetArgsD["targetName"], targetArgsD["srcFiles"], targetArgsD["linkLibs"], targetArgsD["projectName"]).replace("'", '"'))

def WriteData2gnFile(targetsBuildArg):
    count = 0
    with open(OUT_DIR + 'BUILD.gn', 'w+') as gnf:
        gnf.write(config.OHOS_COPYRIGHT)
        for targetArgs in targetsBuildArg:
            if targetArgs:
                targetArgsD = targetArgs._asdict()
                gnf.write(config.OHOS_CONFIG_TEMPLATE.format(targetArgsD["targetName"], targetArgsD["includeDirs"], targetArgsD["compileOptsCC"], targetArgsD["compileOptsCXX"], targetArgsD["macro"]).replace("'", '"'))
                if targetArgsD["targetType"] == config.TARGET_TYPE[0]:  # shared
                    _WriteSharedTarget(gnf, targetArgsD)
                if targetArgsD["targetType"] == config.TARGET_TYPE[1]:  # static
                    _WriteStaticTarget(gnf, targetArgsD)
                if targetArgsD["targetType"] == config.TARGET_TYPE[2]:  # executable
                    _WriteExecutableTarget(gnf, targetArgsD)
                count += 1
            else:
                continue
    return count

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage:")
        print("     python generate_gn_file.py path_of_log")
        exit()
    currentPath = os.getcwd()
    # working dir 需要设置
    config.WorkingDir = currentPath[ : currentPath.find("parse_cmake_log")]
    OUT_DIR = config.WorkingDir
    targetsArg = ParseLogTarget(sys.argv[1])
    ret = WriteData2gnFile(targetsArg)
    print('成功生成 {} 个目标.'.format(ret))
